import Foundation
import Combine

// 车辆控制协议
protocol CarControlProtocol {
    var carStatus: CarStatus { get }
    var statusPublisher: Published<CarStatus>.Publisher { get }
    
    func sendCommand(_ command: CarControlCommand)
    func stopAllMovement()
    func executeCameraOperation(_ operation: CameraOperation)
}

// 车辆控制服务
class CarControlService: ObservableObject, CarControlProtocol {
    // MARK: - 属性
    @Published var carStatus: CarStatus
    var statusPublisher: Published<CarStatus>.Publisher { $carStatus }
    
    // 连接服务
    private var connectionService: CarConnectionService
    
    // 控制命令队列
    private var commandQueue: [CarControlCommand] = []
    
    // 命令定时器
    private var commandTimer: Timer?
    
    // 模拟电池耗电计时器
    private var batteryTimer: Timer?
    
    // MARK: - 初始化方法
    init(connectionService: CarConnectionService) {
        self.connectionService = connectionService
        
        // 初始化车辆状态
        self.carStatus = CarStatus(
            connectionStatus: connectionService.connectionStatus,
            batteryLevel: 1.0,
            currentSpeed: 0.0,
            isRecording: false,
            isCameraActive: true,
            lastCommand: nil,
            lastUpdated: Date()
        )
        
        // 订阅连接状态变化
        connectionService.$connectionStatus
            .sink { [weak self] newStatus in
                self?.carStatus.connectionStatus = newStatus
                self?.carStatus.lastUpdated = Date()
            }
            .store(in: &cancellables)
        
        // 启动电池模拟定时器
        startBatterySimulation()
    }
    
    // 存储取消器
    private var cancellables = Set<AnyCancellable>()
    
    // MARK: - 公共方法
    func sendCommand(_ command: CarControlCommand) {
        // 仅在已连接状态下接受命令
        guard connectionService.isConnected else {
            print("无法发送命令，设备未连接")
            return
        }
        
        // 更新最后一次命令
        carStatus.lastCommand = command
        
        // 根据命令更新车辆状态
        updateCarStatusBasedOn(command)
        
        // 将命令添加到队列
        commandQueue.append(command)
        
        // 发送命令到设备（这里是模拟）
        print("发送命令: \(command.direction.rawValue), 速度: \(command.speed.description)")
        
        // 如果指定了持续时间，设置定时器在指定时间后停止
        if let duration = command.duration {
            DispatchQueue.main.asyncAfter(deadline: .now() + duration) { [weak self] in
                self?.stopAllMovement()
            }
        }
    }
    
    func stopAllMovement() {
        // 发送停止命令
        let stopCommand = CarControlCommand.stop
        sendCommand(stopCommand)
        
        // 清空命令队列
        commandQueue.removeAll()
    }
    
    func executeCameraOperation(_ operation: CameraOperation) {
        // 仅在已连接状态下接受命令
        guard connectionService.isConnected else {
            print("无法执行相机操作，设备未连接")
            return
        }
        
        // 根据操作类型执行不同操作
        switch operation {
        case .takePicture:
            print("执行拍照操作")
            // 模拟拍照效果，可以在这里添加闪光灯或快门声音效果
            
        case .startRecording:
            print("开始录像")
            carStatus.isRecording = true
            
        case .stopRecording:
            print("停止录像")
            carStatus.isRecording = false
            
        case .pan, .tilt, .zoomIn, .zoomOut:
            print("执行相机\(operation.rawValue)操作")
        }
        
        // 更新状态
        carStatus.lastUpdated = Date()
    }
    
    // MARK: - 私有方法
    private func updateCarStatusBasedOn(_ command: CarControlCommand) {
        // 更新速度状态
        switch command.direction {
        case .stop:
            carStatus.currentSpeed = 0.0
        default:
            // 根据速度级别设置实际速度
            carStatus.currentSpeed = command.speed.value
        }
        
        // 更新时间戳
        carStatus.lastUpdated = Date()
    }
    
    // 启动电池模拟
    private func startBatterySimulation() {
        // 每分钟减少1%电量
        batteryTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            
            // 仅在已连接状态下且移动中时消耗电量
            if self.connectionService.isConnected && self.carStatus.currentSpeed > 0 {
                // 移动时消耗更多电量
                let consumptionRate = 0.01 * (1 + self.carStatus.currentSpeed)
                self.carStatus.batteryLevel = max(0, self.carStatus.batteryLevel - consumptionRate)
            } else if self.connectionService.isConnected {
                // 空闲时消耗少量电量
                self.carStatus.batteryLevel = max(0, self.carStatus.batteryLevel - 0.005)
            }
            
            // 更新时间戳
            self.carStatus.lastUpdated = Date()
        }
    }
    
    deinit {
        // 清理定时器
        commandTimer?.invalidate()
        batteryTimer?.invalidate()
    }
} 